package cn.hy.rabbitmq;

import cn.hutool.core.bean.BeanUtil;
import cn.hy.dto.UserDto;
import cn.hy.entity.SecKillGoods;
import cn.hy.mapper.GoodsMapper;
import cn.hy.mapper.SecKillGoodsMapper;
import cn.hy.mq.MqSecKillMessage;
import cn.hy.service.OrderService;
import cn.hy.service.SecKillService;
import cn.hy.vo.GoodsVo;
import cn.hy.vo.SecKillGoodsVo;
import cn.hy.vo.SecKillOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class MQReceiver {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private SecKillService secKillService;

    @RabbitListener(queues = "q.sec_kill")
    public void receive(MqSecKillMessage mqSecKillMessage) {
        log.info("receive message:" + mqSecKillMessage.toString());
        // MqSecKillMessage mqSecKillMessage = JSON.parseObject(message, MqSecKillMessage.class);
        UserDto user = mqSecKillMessage.getUser();
        Long goodsId = mqSecKillMessage.getGoodsId();
        GoodsVo goodsVo = goodsMapper.getGoodsVoByGoodsId(goodsId);
        if (goodsVo == null ){
            throw new RuntimeException("商品不存在");
        }
        Integer stock = goodsVo.getStockCount();
        if (stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        SecKillOrderVo order = orderService.getSecKillOrderByUserIdGoodsId(user.getId(), goodsId);
        if (order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        secKillService.secKill(user,goodsVo);
    }
}
